package com.redstar.expenses;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {

	private Context appContext;
	
	// All Static variables
	// Database Version
	private static final int DATABASE_VERSION = 8;
	 
	// Database Name
	private static final String DATABASE_NAME = "expenseDatabase";
	 
	    // Contacts table name
	    private static final String TABLE_EXPENSES = "expenses";
	 
	    // Contacts Table Columns names
	    private static final String KEY_ID = "id";
	    private static final String KEY_DATE = "date";
	    private static final String KEY_SHOP = "shop";
	    private static final String KEY_ITEM = "item";
	    private static final String KEY_COST = "cost";
	    private static final String KEY_CURR_CODE = "currency";
	    private static final String KEY_LONG = "longitude";
	    private static final String KEY_LAT = "latitude";

	public DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		// TODO Auto-generated constructor stub
		appContext = context;
		
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_EXPENSES + "("
                						+ KEY_ID + " INTEGER PRIMARY KEY," 
                						+ KEY_DATE + " TEXT," 
                						+ KEY_SHOP + " TEXT,"  
                						+ KEY_ITEM + " TEXT,"
                						+ KEY_COST + " DOUBLE,"
                						+ KEY_CURR_CODE + " TEXT,"
                						+ KEY_LONG + " INTEGER, "
                						+ KEY_LAT + " INTEGER " + ")";
        
        db.execSQL(CREATE_CONTACTS_TABLE);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_EXPENSES);
 
        // Create tables again
        onCreate(db);
	}
	
	// CRUD operations
    // Adding new expense
	public void addExpense(Expense exp) {
	    SQLiteDatabase db = this.getWritableDatabase();
	 
	    ContentValues values = getContentValuse(exp);

	    // Inserting Row
	    db.insert(TABLE_EXPENSES, null, values);
	    db.close(); // Closing database connection
	}

	// Updating single expense
	public boolean updateContact(Expense exp) {
	    SQLiteDatabase db = this.getWritableDatabase();
	 
	    ContentValues values = getContentValuse(exp);
	    
	    db.update(TABLE_EXPENSES, values, KEY_ID + " = ?",
	            new String[] { String.valueOf(exp.getID()) });
	    db.close();
	    // updating row
	    return true;
	}
	
    private ContentValues getContentValuse(Expense exp) {
		// TODO Auto-generated method stub
	    ContentValues values = new ContentValues();
	    values.put(KEY_DATE, exp.getTimeDateString());
	    values.put(KEY_SHOP, exp.getShop());
	    values.put(KEY_ITEM, exp.getItem());
	    values.put(KEY_COST, exp.getCost());
	    values.put(KEY_CURR_CODE, exp.getCurrencyCode());
	    values.put(KEY_LONG, exp.getLong());
	    values.put(KEY_LAT, exp.getLat());
	    
	    return values;
	}

	// Getting All Contacts
	 public List<Expense> getAllExpenses() {
	    List<Expense> expenseList = new ArrayList<Expense>();
	    // Select All Query
	    String selectQuery = "SELECT  * FROM " + TABLE_EXPENSES + " ORDER BY " + KEY_DATE + " DESC";
	 
	    SQLiteDatabase db = this.getWritableDatabase();
	    Cursor cursor = db.rawQuery(selectQuery, null);
	 
	    // looping through all rows and adding to list
	    if (cursor.moveToFirst()) {
	        do {
	        	Expense exp = new Expense(null, appContext);
	        	exp.setID(Integer.parseInt(cursor.getString(0)));
	        	exp.setTimeDateString(cursor.getString(1));
	        	exp.setShop(cursor.getString(2));
	        	exp.setItem(cursor.getString(3));
	        	exp.setCost(cursor.getDouble(4));
	        	exp.setCurrencyCode(cursor.getString(5));
	        	exp.setLong(cursor.getInt(6));
	        	exp.setLat(cursor.getInt(7));
	            // Adding contact to list
	        	expenseList.add(exp);
	        } while (cursor.moveToNext());
	    }
	 
	    cursor.close();
	    db.close(); // Closing database connection
	    // return contact list
	    return expenseList;
	}
	 


	public void deleteExpense(int id) {
		// TODO Auto-generated method stub
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_EXPENSES, KEY_ID + " = ?",
                new String[] { String.valueOf(id) });
        db.close();
	}
}
